package com.moneywelcome.loanserviceassembly.apiimpl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.moneywelcome.aliyun.AliyunOssUtil;
import com.moneywelcome.antifraudfacade.api.UserIdcardApi;
import com.moneywelcome.antifraudfacade.form.IdcardForm;
import com.moneywelcome.auth.FaceCompare;
import com.moneywelcome.auth.IdCardNumberQuery;
import com.moneywelcome.baidu.IDcard;
import com.moneywelcome.exceptions.MwcArgsException;
import com.moneywelcome.http.ServletUtil;
import com.moneywelcome.jwt.JWTHelper;
import com.moneywelcome.loanserviceassembly.exceptions.HighRiskException;
import com.moneywelcome.loanservicefacade.api.AuthServiceApi;
import com.moneywelcome.results.Result;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

@RestController
@Slf4j
public class AuthServiceApiImpl implements AuthServiceApi {
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @Autowired
    private IDcard iDcard;

    @Autowired
    private UserIdcardApi idcardApi;

    @Autowired
    private JWTHelper jwtHelper;

    /**
     * 身份认证
     * @param idCard 身份证照片：0人像面，1国徽面
     * @return
     * @throws IOException
     */
//    @GlobalTransactional
    @Override
    public Result idCardAuth(MultipartFile[] idCard) throws IOException {
        log.info("身份证认证");
        if (idCard.length<2) throw new MwcArgsException("身份证上传不完整","idcard_absence");
        // 获取userId
        Integer userId = Integer.valueOf(ServletUtil.getHttpServletRequest().getHeader("userId"));
        //人像面处理
        String originalFilename = idCard[0].getOriginalFilename();
        String fileFormat=originalFilename.substring(originalFilename.lastIndexOf("."));//文件格式后缀
        //上传阿里云oss
        String portraitUrl = aliyunOssUtil.upload("idcard_userid_" + userId + "_portrait" + fileFormat, "vitastar", idCard[0].getInputStream());
        //人像面识别
        HashMap<String, String> portraitMap = iDcard.portraitSideInfo(portraitUrl);
        //身份证风险类型risk_type:normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknown-其他未知情况
        if (!"normal".equals(portraitMap.get("risk_type")))
            return Result.fail("人像面证件类型："+portraitMap.get("risk_type"));
        //图片状态
        if (!"normal".equals(portraitMap.get("image_status")))
            return Result.fail("人像面图片："+portraitMap.get("image_status"));
        //身份证号验证
        boolean b = IdCardNumberQuery.idCardAuth(portraitMap.get("公民身份号码").toString());
        // TODO: 2022/1/6 身份证伪造，加入风控
        if (!b) {
            throw new HighRiskException("虚假的身份证","IDCARD_FORGE");
        }
        //国徽面处理
        //上传阿里云oss
        String emblemUrl = aliyunOssUtil.upload("idcard_userid_" + userId + "_emblem" + fileFormat, "vitastar", idCard[1].getInputStream());
        //国徽面识别
        HashMap<String, String> emblemMap = iDcard.emblemSideInfo(emblemUrl);
        //身份证风险类型risk_type:normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknown-其他未知情况
        if (!"normal".equals(emblemMap.get("risk_type")))
            return Result.fail("国徽面证件类型："+emblemMap.get("risk_type"));
        //身份证反面图状态
        if (!"reversed_side".equals(emblemMap.get("image_status")))
            return Result.fail("国徽面图片："+emblemMap.get("image_status"));

        //调用原子服务，信息存入数据库
        IdcardForm idcardForm = new IdcardForm();
        idcardForm.setUserId(userId);
        idcardForm.setIdcardEmblemImage(emblemUrl);
        idcardForm.setIdcardPortraitImage(portraitUrl);
        idcardForm.setGender(portraitMap.get("性别"));
        idcardForm.setBirthday(changeDateFormat(portraitMap.get("出生")));
        idcardForm.setIdcardNumber(portraitMap.get("公民身份号码"));
        idcardForm.setRealName(portraitMap.get("姓名"));
        idcardForm.setNation(portraitMap.get("民族"));
        idcardForm.setAddress(portraitMap.get("住址"));
        idcardForm.setCardInvalid(changeDateFormat(emblemMap.get("失效日期")));
        idcardForm.setSignAddress(emblemMap.get("签发机关"));
        idcardForm.setCardBeginTime(changeDateFormat(emblemMap.get("签发日期")));
        // 判断是保存还是修改
        if (idcardApi.getIdcard(userId).isSuccess()){
            return idcardApi.modifyIdcard(idcardForm);//修改
        }
        return idcardApi.saveIdcard(idcardForm);//保存
    }

    private String changeDateFormat(String yyyyMMdd){
        String year=yyyyMMdd.substring(0,4);
        String month=yyyyMMdd.substring(4,6);
        String day=yyyyMMdd.substring(6);
        return year+"-"+month+"-"+day;
    }

    /**
     * 人脸对比
     * @param face
     * @return
     */
//    @GlobalTransactional
    @Override
    public Result faceAuth(MultipartFile face) throws IOException {
        log.info("人脸对比");
        // 获取userId
        Integer userId = Integer.valueOf(ServletUtil.getHttpServletRequest().getHeader("userId"));
        //查询身份证
        String idcardNumber = idcardApi.getIdcard(userId).getData().getIdcardNumber();
        //上传文件
        Long next = new SnowflakeGenerator().next();
        String fileName="face_idcard_" + idcardNumber + "_authid_"+ next+".jpg";
        String urlB = aliyunOssUtil.upload(fileName, "vitastar", face.getInputStream());
        String urlA="https://vitastar.oss-cn-chengdu.aliyuncs.com/idcard_"+idcardNumber+".jpg";
        boolean compare = FaceCompare.compare(urlA, urlB);
        log.info("人脸对比结果：{}",compare);
        if (compare){
            return Result.success();
        }else {
            aliyunOssUtil.delete(fileName, "vitastar");
            return Result.fail();
        }
    }



}
